import pool from '../db'
import bcrypt from 'crypto'
import jwt from 'jsonwebtoken'
import { readBody, createError, defineEventHandler, setCookie } from 'h3'
import type { ApiResponse, UserInfo } from '~/types/common'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { username, password } = body
  try {
    // 获取数据库连接
    const connection = await pool.getConnection()
    // 验证用户
    const [user]: any[][] = await connection.execute(
      'SELECT * FROM users WHERE username = ?',
      [username]
    )
    // 修改后的错误处理
    if (!user || (Array.isArray(user) && user.length === 0)) {
      throw createError({
        statusCode: 401,
        statusMessage: '用户名不存在'
      })
    }

    try {
      const hash = bcrypt
        .pbkdf2Sync(password, user[0].salt, 1000, 18, 'sha256')
        .toString('hex')
      const isMatch = hash === user[0].password

      if (!isMatch) {
        throw createError({
          statusCode: 401,
          statusMessage: '密码错误'
        })
      }
    } catch (bcryptError) {
      throw createError({
        statusCode: 401,
        statusMessage:
          bcryptError instanceof Error
            ? bcryptError.message
            : '密码验证服务暂时不可用'
      })
    }

    // 生成访问token (短期)
    const accessToken = jwt.sign(
      { userId: user[0].id },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '5m' }
    )

    // 生成刷新token (长期)
    const refreshToken = jwt.sign(
      { userId: user[0].id, type: 'refresh' },
      process.env.REFRESH_TOKEN_SECRET || 'your-refresh-secret-key',
      { expiresIn: '7d' }
    )

    // 准备用户信息
    const userInfo: UserInfo = {
      id: user[0].id,
      nickname: user[0].nickname,
      avatar: user[0].avatar
    }

    // 设置token到cookie
    setCookie(event, 'accessToken', accessToken, {
      maxAge: 2 * 60, // 2分钟
      sameSite: 'strict',
      secure: process.env.NODE_ENV === 'production'
    })

    setCookie(event, 'refreshToken', refreshToken, {
      maxAge: 7 * 24 * 60 * 60, // 7天
      sameSite: 'strict',
      secure: process.env.NODE_ENV === 'production',
      httpOnly: true
    })

    // 返回响应
    return {
      code: 200,
      message: '登录成功',
      data: {
        accessToken,
        refreshToken,
        user: userInfo
      }
    } as ApiResponse<{
      accessToken: string
      refreshToken: string
      user: UserInfo
    }>
  } catch (error: any) {
    if (error?.statusCode === 401) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: '服务器错误，请稍后再试'
    })
  }
})
